package com.example.loginsystem.api;

import com.example.loginsystem.bean.MyUser;
import com.example.loginsystem.dao.MyUserDAO;
import com.example.loginsystem.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Cheung0
 * Created on 2021/11/27
 */
@RestController
public class UserAPI {

    @Autowired
    private MyUserDAO myUserDAO;

    /**
     * 判断用户登录，这个api会被加入Spring Security拦截器，若用户没有登录会返回无权访问403
     *
     * @return 用户信息
     */
    @GetMapping("/api/islogin")
    public Result<MyUser> isLogin(Authentication authentication) { // 在Controller类方法中加上Spring Security的Authentication类型参数，可以获取当前登录的用户信息例如用户名等等
        Result<MyUser> result = new Result<>();
        MyUser myUser = null;
        // 判断是否登录
        if (!authentication.isAuthenticated()) {
            result.setResultFailed("用户未登录！");
            return result;
        }
        // 获取当前登录的用户信息
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        try {
            // 获取用户名并查询用户
            myUser = myUserDAO.getByUsername(userDetails.getUsername());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (myUser == null) {
            result.setResultFailed("用户无效！");
            return result;
        }
        result.setResultSuccess("用户已经登录！", myUser);
        return result;
    }

}
